//批量设置商品渠道
import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { queryTypeChannel } from '@/services/common';
import { uniq, countBy, uniqBy, cloneDeep } from 'lodash';
import { getCurrentUser } from '@/utils/authority';
import {
  Form,
  Button,
  message,
  Input,
  Checkbox,
  Select,
  Row,
  Col,
  Tooltip,
} from 'antd';
// import { addChannel, editChannel } from '../../service';

const layout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 15,
  },
};

//判断某个数出现的次数
function countOccurrences(arr, target) {
  const counts = countBy(arr);
  return counts[target] || 0;
}

const { Option } = Select;

const BatchSetChannel = ({
  channelSwitch,
  combinList,
  channelClose,
  handleOk,
}) => {
  const [combinArr, setCombinArr] = useState([]); //组合商品下拉
  const [isChecked, setIsChecked] = useState(false); //仅设置默认是否选中
  const [channelList, setChannelList] = useState([]); //渠道下拉
  const [combinValue, setCombinValue] = useState([]); //选择的商品组合
  const [channelType, setChannelType] = useState(1); //获取渠道下拉的type
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (channelSwitch) {
      form.resetFields();
    }
  }, [channelSwitch]);

  useEffect(() => {
    const arr = [];
    if (combinList.length) {
      combinList.forEach((item) => {
        if (item.checked) {
          arr.push(handleDealSubGood(item.subGoodsArr));
        }
      });
    }
    const newArr = uniqBy(arr, 'type');
    setCombinArr(newArr);
    setCombinValue(newArr.map((z) => z.type));
  }, [combinList]);

  useEffect(() => {
    if (combinValue.length > 0) {
      getChannelList(combinValue);
    } else {
      setChannelList([]);
    }
  }, [combinValue]);

  //处理子商品的商品组合
  const handleDealSubGood = (arr) => {
    const list = arr.map((item) => item.deliverType);
    const occurrences = countOccurrences(list, 4); //供应商直发选了几种
    if (list.includes(4)) {
      //存在商家直发
      const list2 = uniq(list);
      if (occurrences == 1) {
        //只选了一个供应商直发
        if (list2.length == 1) {
          //全部是供应商直发
          return {
            name: '供应商直发',
            type: 4,
          };
        } else if (list2.length == 2) {
          if (list2.includes(3)) {
            //存在库存
            return {
              name: '库存+供应商直发',
              type: 6,
            };
          } else {
            return {
              name: '拿货+供应商直发',
              type: 7,
            };
          }
        } else {
          //数量为3
          return {
            name: '拿货+库存+供应商直发',
            type: 8,
          };
        }
      } else {
        if (list2.length == 1) {
          //全部是供应商直发
          return {
            name: '供应商直发+供应商直发',
            type: 5,
          };
        } else if (list2.length == 2) {
          if (list2.includes(3)) {
            //存在库存
            return {
              name: '库存+供应商直发+供应商直发',
              type: 9,
            };
          } else {
            return {
              name: '拿货+供应商直发+供应商直发',
              type: 10,
            };
          }
        } else {
          //数量为3
          return {
            name: '拿货+库存+供应商直发+ 供应商直发',
            type: 11,
          };
        }
      }
    } else {
      //不存在供应商直发
      const list2 = uniq(list);
      if (list2.length == 1) {
        //单一组合商品
        if (list2[0] == 3) {
          // 全部是库存商品
          return {
            name: '库存商品',
            type: 1,
          };
        } else {
          // 全部是拿货商品
          return {
            name: '拿货商品',
            type: 2,
          };
        }
      } else {
        //组合商品
        if (list2.includes(3)) {
          // 库存+拿货
          return {
            name: '库存+拿货',
            type: 3,
          };
        } else {
          // 1和2的组合全部是拿货
          // 全部是拿货商品
          return {
            name: '拿货商品',
            type: 2,
          };
        }
      }
    }
  };

  //批量获取渠道下拉列表
  const getChannelList = async (arr) => {
    let type = null;
    if (
      //存在直发组合无法选渠道
      combinValue.includes(5) ||
      combinValue.includes(6) ||
      combinValue.includes(7) ||
      combinValue.includes(8) ||
      combinValue.includes(9) ||
      combinValue.includes(10) ||
      combinValue.includes(11)
    ) {
      type == null;
    } else {
      if (arr.length == 1) {
        //单个商品组合
        if (arr.includes(1)) {
          //库存
          type = 1;
        } else if (arr.includes(2)) {
          //拿货
          type = 8;
        } else if (arr.includes(3)) {
          //库存+拿货
          type = 1;
        } else if (arr.includes(4)) {
          //供应商直发
          type = 0;
        }
      } else {
        // 拿货 库存； 拿货 拿货 + 库存； 库存 拿货+ 库存；
        if (arr.includes(4)) {
          //存在供应商直发
          type = null;
        } else {
          type = 1;
        }
      }
    }
    setChannelType(type);
    // const type = getChannelType(val);
    if (type) {
      setLoading(true);
      const { data, success } = await queryTypeChannel({
        isDeleted: 0,
        type,
        uuid: getCurrentUser().uuid,
      });
      if (success) {
        setChannelList(data);
      }
      setLoading(false);
    } else {
      if (type == 0) {
        const arr = [{ id: 0, channelName: `供应商(直发)` }];
        setChannelList(arr);
      }
    }
  };

  const cancel = () => {
    channelClose();
  };

  const channelOk = () => {
    form
      .validateFields()
      .then(async (val) => {
        const list = [];
        const arr = cloneDeep(combinList);
        arr.forEach((item) => {
          list.push({
            ...item,
            channelId: item.checked ? val.channelId : '',
          });
        });
        handleOk(list, channelType);
      })
      .catch((err) => {});
  };

  //点击仅设置
  const onChange = (e) => {
    setIsChecked(e.target.checked);
  };

  //修改组合商品
  const combinTypeChange = (val) => {
    setCombinValue(val);
  };

  //商品组合的下拉
  const combinOptions = combinArr.map((d, index) => (
    <Option value={d.type} key={index} label={d.name}>
      <Tooltip title={d.name}>{d.name}</Tooltip>
    </Option>
  ));

  const optionChannel = channelList.map((item) => {
    return (
      <Option key={item.id} value={item.id}>
        {item.channelName}
        {item.id == 0
          ? null
          : getCurrentUser().uuid == item.uuid
          ? '(自发)'
          : '(第三方)'}
      </Option>
    );
  });

  return (
    <>
      <CommonModal
        title={'批量设置发货渠道'}
        visible={channelSwitch}
        onCancel={cancel}
        width={450}
        footer={[
          <Button key={1} onClick={cancel} loading={loading}>
            取消
          </Button>,
          <Button key={2} type="primary" onClick={channelOk} loading={loading}>
            确定
          </Button>,
        ]}
      >
        <div className="form_box">
          <Form
            name="btach_set_channel"
            {...layout}
            form={form}
            initialValues={{}}
          >
            <Form.Item label="商品组合">
              <Row gutter={8}>
                <Col span={16}>
                  <Select
                    allowClear
                    mode="multiple"
                    disabled={!isChecked}
                    onChange={combinTypeChange}
                    value={combinValue}
                  >
                    {combinOptions}
                  </Select>
                </Col>
                <Col span={8}>
                  <Checkbox onChange={onChange} checked={isChecked}>
                    仅设置
                  </Checkbox>
                </Col>
              </Row>
            </Form.Item>

            <Form.Item label="发货渠道" name="channelId">
              <Select
                // value={channelId}
                // size="small"
                // onDropdownVisibleChange={() => handleGetChannel(subGoodsArr)}
                // onChange={(e) => handleChangeChannel(e, obj)}
                placeholder="请选择发货渠道"
              >
                {optionChannel}
              </Select>
            </Form.Item>
          </Form>
        </div>
      </CommonModal>
      <CommonLoading loading={loading} />
    </>
  );
};

export default BatchSetChannel;
